package com.android.measuringimportanceoflectureslides.data;

import com.android.measuringimportanceoflectureslides.MainActivity;
import com.android.measuringimportanceoflectureslides.R;

import android.app.Activity;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class Database extends ListActivity {
	
	private DatabaseManager mDatabaseManager;
	private SQLiteDatabase mDatabase;
	private Context mContext;
	private ListView mListView;
	
	public Database(Context context, ListView listView){
		this.mContext = context;
		this.mListView = listView;
	}

	public void  databaseOnCreate(){
		//this-> onCreate, mContext if its a own method!
		mDatabaseManager = new DatabaseManager(mContext);
	}

	public void databaseOnPause() {
		mDatabase.close();
		//this-> onCreate, mContext if its a own method!
		if(MainActivity.debugDB == 1){
			Toast.makeText(mContext, "Database closed", Toast.LENGTH_SHORT).show();
		}
	}

	public void databaseOnResume() {
		mDatabase = mDatabaseManager.getReadableDatabase();
		//this-> onCreate, mContext if its a own method!
		if(MainActivity.debugDB == 1){
			Toast.makeText(mContext, "Database opened", Toast.LENGTH_SHORT).show();
		}
		loadClass();
	}

	private void loadClass() {
		//Returns a curser on the first data item
		Cursor classCursor = mDatabase.query(
										"klassen", 
										new String[] {"_id", "name"}, 
										null, null, null, null, "name");
		startManagingCursor(classCursor);
		
		SimpleCursorAdapter classAdapter = 
				new SimpleCursorAdapter(
						mContext, 
						android.R.layout.simple_list_item_1, 
						classCursor, 
						new String[] {"name"}, 
						new int[] { android.R.id.text1}
					);
		mListView.setAdapter(classAdapter);
	}
	
	public void addFileNameToDatabase ( String fileName){
		ContentValues value = new ContentValues();
		value.put("name",fileName);
		mDatabase.insert("klassen", null, value);
		loadClass();
	}
}

